<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/6/7 0007
 * Time: 下午 3:29
 */
namespace app\admin\controller;

use app\common\model\Order as OrderModel;
use app\common\model\Proofrefund;
use app\common\model\Refundorder;
use app\common\validate\TenantRefund;
use app\lib\exception\ParameterException;
use app\admin\model\Operator as OperatorModel;

class Refund extends Base
{

    /*public function index(){
        $tenantId = session('TENANT_ID');
        $Refund = new Refundorder();
        $field = 'id,orderNO,productId,status,create_time,endDate,out_refund_no,refund_fee,content,expressName,expressNo,oldTotal,expressNameT,expressNoT';
        $Refundorder = $Refund->where('tenantId',$tenantId)->field($field)->order('create_time desc')->paginate(config("paginate['list_rows']"));
        if($Refundorder){
            foreach ($Refundorder as &$v){
                $field = 'id,create_time,payMethod,total,total_count,status';
                $order = \app\common\model\Order::where('orderNO',$v['orderNO'])->field($field)->find();
                $v['order'] = $order;
                $v['order']['orderproductDetail'] = $order->orderproductDetail;
            }
            //return show('1','ok',$Refundorder);
            $page = $Refundorder->render();
            $this->assign('order',$Refundorder);
            $this->assign('page',$page);
            return $this->fetch();
        }
    }*/

    public function index(){
        if(!$this->checkStore()) {
            return $this->fetch('public/alert');
        }
        
        $tenantId = session('TENANT_ID');
        $param = $this->request->param();
        // 获取所有门店
        $store = model('store')->where(['tenantId' => $tenantId])->order('createDate')->select();
        $storeId = isset($param['id']) ? $param['id'] : $store[0]['id'];

        $this->assign('store',$store);
        $this->assign('storeId',$storeId);

        return $this->fetch();
    }

    /**
     * 获取所有订单
     */
    public function getRefundList(){
        $request = $this->request;
        $param = $request->param();

        if(session('member')['roleType'] == 2 ) {
            $storeId = session('member')['storeId'];
        } else {
            $store = model('store')->where(['tenantId' => session('TENANT_ID')])->order('createDate')->find();
            $storeId = $store->id;
        }

        $start = $param['start'];  // 每页起始条数
        $length = $param['length'];  // 每页显示条数
        $columns = $param['order'][0]['column'];
        $order = $param['columns'][$columns]['data'].' '.$param['order'][0]['dir'];  //排序条件

        if($param['storeId']){
            $storeId = $param['storeId'];
        }
        $where = [
            'tenantId' => session('TENANT_ID'),
            'storeId' => $storeId
        ];
        if($param['search']['value']) {
            $filter = json_decode($param['search']['value'],true);
            if($filter['storeId']){
                $where['storeId'] = $filter['storeId'];
            }
            if(isset($filter['status']) && $filter['status']){
                $where['status'] = $filter['status'];
            }
            if(isset($filter['orderNO']) && trim($filter['orderNO'])){
                $where['orderNO'] = ['like', '%' . trim($filter['orderNO']) . '%'];
            }
            if(isset($filter['begin_time']) && $filter['begin_time']){
                $where['create_time'] = ['egt', strtotime($filter['begin_time'])];
            }
            if(isset($filter['end_time']) && $filter['end_time']){
                $where['create_time'] = ['lt', strtotime($filter['end_time']) + 24*60*60];
            }
            if(isset($filter['begin_time']) && $filter['begin_time'] && isset($filter['end_time']) && $filter['end_time']){
                $where['create_time'] = [['egt', strtotime($filter['begin_time'])], ['lt', strtotime($filter['end_time']) + 24*60*60], 'and'];
            }
        }

        $refund = new Refundorder();
        $field = 'id,orderNO,productId,status,create_time,endDate,out_refund_no,refund_fee,content,expressName,expressNo,oldTotal,expressNameT,expressNoT';
        $list = $refund->where($where)->limit($start, $length)->order($order)->field($field)->select();
        foreach ($list as $key => $val) {
            $field = 'id,create_time,payMethod,total,total_count,userPhone,status';
            $order = OrderModel::where('orderNO', $val['orderNO'])->field($field)->find();
            $item = $list[$key];
            $item->productImg = isset($order->orderproductDetail[0]['productImg']) ? $order->orderproductDetail[0]['productImg'] : '';
            $item->userPhone = isset($order->userPhone) ? $order->userPhone : '';
        }
        $count = $refund->where($where)->count();

        $result = [
            'status' => '1',
            'draw' => $param['draw'],
            'data' => $list,
            'recordsFiltered' => $count,
            'recordsTotal' => $count,
        ];

        return json($result);
    }

    /**
     * 导出数据
     */
    public function export(){
        $param = $this->request->param();

        $where = [
            'tenantId' => session('TENANT_ID'),
        ];
        if(!empty($param['storeId'])){
            $where['storeId'] = $param['storeId'];
        }
        if(!empty($param['status'])){
            $where['status'] = $param['status'];
        }
        if(!empty($param['orderNO'])){
            $where['orderNO'] = ['like', '%'.$param['orderNO'].'%'];
        }
        if(!empty($param['begin_time'])){
            $where['create_time'] = ['egt', strtotime($param['begin_time'])];
        }
        if(!empty($param['end_time'])){
            $where['create_time'] = ['elt', strtotime($param['end_time'])];
        }
        if(!empty($param['begin_time']) && !empty($param['end_time'])){
            $where['create_time'] = [['egt', strtotime($param['begin_time'])], ['lt', strtotime($param['end_time']) + 24*60*60], 'and'];
        }

        $refund = new Refundorder();
        $data = $refund->where($where)->order('create_time', 'asc')->select();
        if(count($data) <= 0){
            $this->error('没有数据！', url('admin/refund/index'));
        }
        foreach ($data as $key => $val) {
            // 图片
            $field = 'id,create_time,payMethod,total,total_count,status';
            $order = OrderModel::where('orderNO', $val['orderNO'])->field($field)->find();
            $val['productImg'] = isset($order->orderproductDetail[0]['productImg']) ? $order->orderproductDetail[0]['productImg'] : '';
            $val['userPhone'] = isset($order->userPhone) ? $order->userPhone : '';
            // 退款金额
            $val['refund_fee'] = $val['refund_fee'] / 100 . ' 元';
            // 订单状态
            switch ($val['status']) {
                case 1: $val['status'] = '拒绝售后'; break;
                case 2: $val['status'] = '已退款'; break;
                case 3: $val['status'] = '删除'; break;
                case 4: $val['status'] = '申请中'; break;
                case 5: $val['status'] = '取消售后'; break;
                default : break;
            }
        }
        $cellName = array(
            'A' => ['productImg', '图片'],
            'B' => ['orderNO', '订单号'],
            'C' => ['refund_fee', '退款金额(元)'],
            'D' => ['userPhone', '手机号'],
            'E' => ['create_time', '申请时间'],
            'F' => ['status', '状态'],
        );

        $filePath = ROOT_PATH . 'public' . DS . 'upload' . DS . 'csv' . DS . 'refund' . DS . date('Y-m-d');
        $fileName = $filePath . '/refund_' . date('y-m-d-H-i-s');

        $excel = new Excel();
        $excel->exportExcel('售后', $data, $cellName, $filePath, $fileName);

        return redirect('admin/refund/index');
    }

    /**
     * 订单售后详情
     * @param $id
     * @return mixed
     * @throws ParameterException
     */
    public function RefundDetails($id){
        if(empty($id)){
            throw new ParameterException([
                'msg' => '该订单不存在'
            ]);
        }
        $Refundordermodel = new Refundorder();
        $field = 'id,orderNO,productId,status,create_time,endDate,out_refund_no,refund_fee,reason,content,expressName,expressNo,oldTotal,expressNameT,expressNoT,orderProductDetailId';
        $Refundorder = $Refundordermodel->where('id',$id)->field($field)->find();
        //new Proofrefund()

        $field = 'id,orderNO,create_time,payMethod,total,total_count,status,linkType,storeId,payDate,type,userName,userPhone,deliverAddress,content';
        $order = \app\common\model\Order::where('orderNO',$Refundorder->orderNO)->field($field)->find();
        $Refundorder['order'] = $order;
        $Refundorder['order']['orderproductDetail'] = $order->orderproductDetail;
        $i = 0;
        $Refundorder['order']['RefundorderproductDetail'] = [];
        foreach ($Refundorder['order']['orderproductDetail'] as $v){
            if($v['id'] == $Refundorder->orderProductDetailId){
                $Refundorder['order']['RefundorderproductDetail'] = $v;
            }
            $i++;
        }
        $refundImg = [];
        $Proofrefund = Proofrefund::where('refundId',$Refundorder->id)->find();
        if($Proofrefund){
            $refundImg = explode(',',$Proofrefund->imgUrl);
        }
        unset($Refundorder['order']['orderproductDetail']);
        //return show('1','ok',$Refundorder);

        //店铺信息
        $Store = \app\admin\model\Store::get($order->storeId);
        $tenant = \app\admin\model\Tenant::get($Store->tenantId);
        $tenantname = $tenant->name . '-' . $Store->name;

        //员工
        $OperatorModel = new OperatorModel();
        $staff = $OperatorModel->where(['storeId'=>$order->storeId])->select();
        $this->assign('order',$order);
        $this->assign('orderproductDetail',$Refundorder['order']['RefundorderproductDetail']);
        $this->assign('staff',$staff);
        $this->assign('tenantname',$tenantname);
        $this->assign('Refundorder',$Refundorder);
        $this->assign('refundImg',$refundImg);
        return $this->fetch();
    }


    /**
     * 处理售后
     * @return \think\response\Json
     * @throws ParameterException
     */
    public function doRefund(){
        //参数商户退款单号
        $tenantid = session('TENANT_ID');
        if(!$tenantid){
            throw new ParameterException([
                'msg' =>  '权限异常'
            ]);
        }

        (new TenantRefund())->goCheck();

        $refund = new \app\admin\service\Refund(input('post.'));

        return $refund->actionrefund();
    }

}